import {
    Form, Input,
    Button, Checkbox,
    message, notification,
    Row, Col
} from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import {
    UserOutlined, LockOutlined,
    MobileOutlined, CheckCircleOutlined
} from '@ant-design/icons';
import './login.scss'
import logo from '@/assets/images/login_logo.png'
import { ValidationRules, setRouterByRoles } from '@/utils'
import { storage } from '@/utils/storage'
import { connect } from 'react-redux'
import routes from '@/routes'
import api from '@/api/apiList'
import config from '@/config'
const { setting } = config
const YzhLoginForm = (props) => {
    const [loading, setLoading] = useState(false)
    const [disabled, setDisabled] = useState(false)
    const [state, setState] = useState({
        loginModeType: 1001,
        password: '',
        codeText: '获取验证码'
    })
    let timer = null
    useEffect(() => {
        let t = storage.get('countDown')
        t && t !== null && getCountDown(t)
        // if (loginModeType === 1002) {
        // }
        return () => {
            clearInterval(timer)
        }
    }, [state.loginModeType])
    const [form] = Form.useForm();
    const { history, location } = props
    const { loginModeType, password, codeText } = state
    let redirect = (location.query && location.query.redirect) || '/'
    // console.log('location: ', location);
    // 登陆成功，初始化数据
    const initUseInfo = async (res) => {
        const args = {
            message: '登录成功！',
            top: 64,
            icon: <CheckCircleOutlined className="primary" />,
            description:
                `欢迎使用${config.setting.title}服务`,
            duration: 3,
        };
        const getPermissionCodes = (data) => {
            let menuList = data.menuList && JSON.parse(data.menuList) || []
            let btnMap = data.btnMap && JSON.parse(data.btnMap) || {}
            let dataMap = data.dataMap && JSON.parse(data.dataMap) || {}
            return setRouterByRoles(menuList, btnMap, dataMap)
        }
        try {
            storage.set('token', encodeURIComponent(res.result.token), 'cookie')
            let data = await api.userCenter.user.getMenuByToken({
                token: res.result.token,
                userId: res.result.userId,
                // appCode: 'yzh-user-service'
            })
            props.setUserInfo({
                ...res.result,
                name: res.result.name || res.result.loginName,
                roleId: '',
                permissionCodes: []
            })
            if (data.result !== null) {
                const { permissionCodes } = getPermissionCodes(data.result)
                props.setUserInfo({
                    ...res.result,
                    name: data.result.name,
                    deptName: data.result.deptName,
                    roleName: data.result.roleName,
                    email: data.result.email,
                    phone: data.result.roleName,
                    roleId: data.result.roleId,
                    permissionCodes
                })
                let tabList = storage.get('tabList')
                if (tabList && tabList !== null) {
                    console.log(tabList, 'tabList');
                    tabList = tabList.filter(el => !!el.meta && el.meta.roles && el.meta.roles.filter(code => permissionCodes.includes(code)).length || el.path === '/')
                }
            } else {
                storage.set('tabList', routes.filter(el => el.affix).map(el => ({
                    key: el.path,
                    title: el.meta.title,
                    closable: !el.affix,
                    meta: el.meta
                })))
            }
            props.changeTabs(redirect)
            history.push(redirect)
            notification.open(args);
        } catch (error) {
            storage.remove('token', 'cookie')
            console.log(error);
        }
    }
    const onFinish = async () => {
        form
            .validateFields()
            .then(async (values) => {
                // setLoading(false)
                // initUseInfo({ result: { token: 'yzh-user-center', ...values }, success: true })
                // console.log('Received values of form: ', values);
                setLoading(true)
                let res = await api.userCenter.user.login({ ...values, loginModeType: state.loginModeType })
                setLoading(false)
                if (res && res.success) {
                    initUseInfo(res, values)
                }
            })
            .catch((info) => {
                console.log('Validate Failed:', info);
            });
    };
    const getCountDown = (t) => {
        t = (!t || t === null) ? 59 : t
        t = t < 10 ? '0' + t : t
        setDisabled(true)
        setState({
            ...state,
            codeText: t + 's后获取'
        })
        timer = setInterval(() => {
            t--
            t = t < 10 ? '0' + t : t
            setState({
                ...state,
                codeText: t + 's后获取'
            })
            storage.set('countDown', parseInt(t))
            if (parseInt(t) < 1) {
                t = 59
                clearInterval(timer)
                storage.remove('countDown')
                setDisabled(false)
                setState({
                    ...state,
                    codeText: '获取验证码'
                })
            }
        }, 1000);
    }
    const getMsgCode = () => {
        form
            .validateFields(['username'])
            .then(async (values) => {
                let res = await api.userCenter.user.msgCode({ phone: values.username })
                if (res && res.success) {
                    res && res.success && message.success('操作成功')
                    getCountDown(storage.get('countDown'))
                }
            })
            .catch((info) => {
                console.log('Validate Failed:', info);
            });
    }
    const onWayChange = () => {
        form.resetFields()
        setState({
            ...state,
            loginModeType: loginModeType === 1001 ? 1002 : 1001
        })
    }
    return (
        <div className="yzh-login">
            <div className="yzh-login-main">
                <div className="yzh-login-logo">
                    <img src={logo} alt="" className="logo" />
                </div>
                <Row align="center" justify="center">
                    <Col flex={2} className="yzh-login-bg">
                        <div className="yzh-login-mask"></div>
                    </Col>
                    <Col flex={2} className="yzh-login-container">
                        <Form
                            name="normal_login"
                            form={form}
                            className="yzh-login-form"
                            initialValues={{
                                remember: true,
                            }}
                            labelAlign="right"
                            labelCol={{ span: 4, offset: 0 }}
                            onFinish={onFinish}
                        >
                            <Form.Item style={{ marginBottom: 32 }}>
                                <div className="yzh-login-form-item header">
                                    <h3 className="title">{config.setting.title}</h3>
                                </div>
                            </Form.Item>
                            <Form.Item style={{ marginBottom: 32 }}>
                                <div className="yzh-login-form-item login-way">
                                    <span onClick={onWayChange} className={`name ${loginModeType === 1001 && 'active'}`}>账号登录</span>
                                    <span onClick={onWayChange} className={`name ${loginModeType === 1002 && 'active'}`}>短信登录</span>
                                </div>
                            </Form.Item>
                            {loginModeType === 1001 && <React.Fragment>
                                <Form.Item
                                    name="username"
                                    // label="用户名"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入用户名'
                                            // validator: (rule, value) => {
                                            //     return new ValidationRules({
                                            //         prop: 'account',
                                            //         message: '用户名',
                                            //         type: 'account',
                                            //         limit: 15,
                                            //         inputControll: true,
                                            //         value
                                            //     }).validate(rule, value)
                                            // },
                                        },
                                    ]}
                                >
                                    <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入用户名" />
                                </Form.Item>
                                <Form.Item
                                    name="password"
                                    style={{ marginBottom: 38 }}
                                    // label={<span>密 &nbsp; 码</span>}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入密码',
                                            // validator: (rule, value) => {
                                            //     return new ValidationRules({
                                            //         prop: 'password',
                                            //         message: '密码',
                                            //         type: 'password',
                                            //         limit: 15,
                                            //         inputControll: true,
                                            //         value
                                            //     }).validate(rule, value)
                                            // },
                                        },
                                    ]}
                                >
                                    <Input.Password
                                        prefix={<LockOutlined className="site-form-item-icon" />}
                                        // placeholder={setting.message.password}
                                        placeholder="请输入密码"
                                    />
                                </Form.Item>
                                {/* <Form.Item>
                                <div className="yzh-login-form-item">
                                    <Form.Item name="remember" valuePropName="checked" noStyle>
                                        <Checkbox>记住账号</Checkbox>
                                    </Form.Item>
                                    <Link className="login-form-forgot" to="/">
                                        忘记密码？
                                    </Link>
                                </div>
                            </Form.Item> */}
                            </React.Fragment>}
                            {loginModeType === 1002 && <React.Fragment>
                                <Form.Item
                                    name="username"
                                    // label="手机号"
                                    rules={[
                                        {
                                            required: true,
                                            validator: (rule, value) => {
                                                return new ValidationRules({
                                                    prop: 'username',
                                                    message: '手机号',
                                                    type: 'phone',
                                                    limit: 11,
                                                    inputControll: true,
                                                    value
                                                }).validate(rule, value)
                                            },
                                        },
                                    ]}
                                >
                                    <Input prefix={<MobileOutlined className="site-form-item-icon" />} placeholder="请输入手机号" />
                                </Form.Item>
                                <Form.Item
                                    name="password"
                                    // label="验证码"
                                    style={{ marginBottom: 38 }}
                                    rules={[
                                        {
                                            required: true,
                                            message: '短信验证码!',
                                        },
                                    ]}
                                >
                                    <Input
                                        type="text"
                                        maxLength={6}
                                        addonAfter={<Button type="link" disabled={disabled} onClick={() => getMsgCode()}>{codeText}</Button>}
                                        placeholder="短信验证码"
                                    />
                                </Form.Item>
                            </React.Fragment>}
                            <Form.Item style={{ marginBottom: 0 }}>
                                <div className="yzh-login-form-item submit">
                                    <Button type="primary" loading={loading} htmlType="submit" className="login-form-button tc">
                                        登录
                                    </Button>
                                </div>
                            </Form.Item>
                        </Form>
                    </Col>
                </Row>
            </div>
        </div>
    );
};
//需要渲染什么数据
function mapStateToProps (state) {
    return {
        panes: state.app.panes,
        activeKey: state.app.activeKey,
        userInfo: state.app.userInfo,
    }
}
//需要触发什么行为
function mapDispatchToProps (dispatch, props) {
    return {
        filterTabs: (type, history) => dispatch({
            type: 'filterTabs', value: type,
            history
        }),
        changeTabs: (activeKey) => dispatch({
            type: 'changeTabs',
            activeKey
        }),
        setUserInfo: (value) => {
            dispatch({
                type: 'setUserInfo',
                value,
                ...props
            })
        },
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(YzhLoginForm)